<template>
  <div>
    <!-- 中心区域 -->
    <a-col :span="24">
      <a-card>
        <a-button type="primary" class="editable-add-btn" @click="handleAdd">新增</a-button>
        <!-- 列表 -->
        <a-table bordered :columns="columns" :data-source="dataSource" :pagination="pagination" rowKey="id" ref="tableRef">
          <template v-for="col in ['biaoduanmingcheng', 'biaoduanleixing', 'zhaobiaoren', 'dailijigou', 'zhaobiaoneirong', 'zhaobiaowj', 'zhongbiaoren', 'zhongbiaojia', 'hetongqiandingshijian', 'hetongwj', 'zbdwfzr', 'zbdwfzrphone']" #[col]="{ text, record }" :key="col">
            <div>
              <template  v-if="editableData[record.id] && ['biaoduanmingcheng', 'biaoduanleixing', 'zhaobiaoren', 'dailijigou', 'zhaobiaoneirong', 'zhongbiaoren', 'zhongbiaojia', 'zbdwfzr', 'zbdwfzrphone'].includes(col)">
                <a-input v-model:value="editableData[record.id][col]" style="margin: -5px 0" />
              </template>
              <template v-else-if="editableData[record.id] && ['hetongqiandingshijian'].includes(col)">
                <a-date-picker v-model:value="editableData[record.id][col]" valueFormat="YYYY-MM-DD" style="width: 110px;"/>
              </template>
              <template v-else-if="editableData[record.id] && ['zhaobiaowj', 'hetongwj'].includes(col)">
                <a-upload action="http://localhost:9292/api/sys/oss/upload?bcpath=bdxx" :multiple="false" :headers="headers" @change="handleChange" >
                  <a-button type="primary" size="small" @click="handleClick(col)">
                    <upload-outlined></upload-outlined>
                    上传
                  </a-button>
                </a-upload>
              </template>
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>

          <template #operation="{ record }">
            <div style="width: 100px;">
                <span class="editable-row-operations">
                <span v-if="editableData[record.id]">
                  <a @click="baocun(record.id)">保存</a>
                  <a-popconfirm title="确定取消吗？" @confirm="cancel(record.id)">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span v-else>
                  <a @click="edit(record.id)">编辑</a>
                </span>
              </span>
              <a-popconfirm
                v-if="dataSource.length"
                title="确定删除吗？"
                @confirm="onDelete(record.id)"
              >
                <a>删除</a>
              </a-popconfirm>
            </div>
          </template>
        </a-table>
      </a-card>
    </a-col>
    <page-footer></page-footer>
  </div>
</template>
<script>
  import {reactive, ref, toRaw} from 'vue';
  import {page, remove, save} from '@/api/module/sg_biaoduan';
  import {cloneDeep} from "lodash-es";
  import {message} from "ant-design-vue";
  import { v4 as uuidv4 } from "uuid";
  import global from '../global/global';

  const removeKey = "remove";

  export default {
    setup(){
      const tableRef = ref();
      const editableData = reactive({});

      /// 列配置
      const columns = [
        {dataIndex: "biaoduanmingcheng", key: "biaoduanmingcheng", title: "标段名称", slots: {customRender: 'biaoduanmingcheng'}},
        {dataIndex: "biaoduanleixing", key: "biaoduanleixing", title: "标段类型", slots: {customRender: 'biaoduanleixing'}},
        {dataIndex: "zhaobiaoren", key: "zhaobiaoren", title: "招标单位", slots: {customRender: 'zhaobiaoren'}},
        {dataIndex: "dailijigou", key: "dailijigou", title: "招标代理机构", slots: {customRender: 'dailijigou'}},
        {dataIndex: "zhaobiaoneirong", key: "zhaobiaoneirong", title: "招标内容", slots: {customRender: 'zhaobiaoneirong'}},
        {dataIndex: "zhaobiaowj", key: "zhaobiaowj", title: "招标文件", slots: {customRender: 'zhaobiaowj'}},
        {dataIndex: "zhongbiaoren", key: "zhongbiaoren", title: "中标单位", slots: {customRender: 'zhongbiaoren'}},
        {dataIndex: "zhongbiaojia", key: "zhongbiaojia", title: "中标价（万元）", slots: {customRender: 'zhongbiaojia'}},
        {dataIndex: "hetongqiandingshijian", key: "hetongqiandingshijian", title: "合同签订日期", slots: {customRender: 'hetongqiandingshijian'}},
        {dataIndex: "hetongwj", key: "hetongwj", title: "合同（扫描件）", slots: {customRender: 'hetongwj'}},
        {dataIndex: "zbdwfzr", key: "zbdwfzr", title: "中标单位联系人", slots: {customRender: 'zbdwfzr'}},
        {dataIndex: "zbdwfzrphone", key: "zbdwfzrphone", title: "中标单位联系人电话", slots: {customRender: 'zbdwfzrphone'}},
        {key: 'operation', title: '操作', width: 100, slots: {customRender: 'operation'}},
      ]

      ///数据来源
      const dataSource = ref([]);
      page({"xiangmuid": global.xmid}).then((response) => {
        dataSource.value = response.data.record;
      });

      /// 分页参数
      const pagination = {
        pageNum: 1,
        pageSize: 10,
      }

      const handleAdd = () => {
        let random = uuidv4().replaceAll("-", "");
        let xmid = global.xmid;
        const addData = {
          id: random,
          xiangmuid: xmid,
          biaoduanmingcheng: '',
          biaoduanleixing: '',
          zhaobiaoren: '',
          dailijigou: '',
          zhaobiaoneirong: '',
          zhaobiaowj: '',
          zhongbiaoren: '',
          zhongbiaojia: '',
          hetongqiandingshijian: '',
          hetongwj: '',
          zbdwfzr: '',
          zbdwfzrphone: '',
        };
        dataSource.value.push(addData);
        edit(random);
      };

      const cancel = key => {
        delete editableData[key];
      };

      const onDelete = key => {
        dataSource.value = dataSource.value.filter(item => item.id !== key);
        remove({"id": key}).then((response) => {
          if(response.success){
            message.success({content: "删除成功", key: removeKey, duration: 1})
          } else {
            message.error({content: "删除失败", key: removeKey, duration: 1})
          }
        })
      };

      const edit = key => {
        editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.id)[0]);
        handleKey = key
      };
      const baocun = key => {
        Object.assign(dataSource.value.filter(item => key === item.id)[0], editableData[key]);
        save(toRaw(editableData[key])).then((response) => {
          if(response.success){
            message.success({ content: '提交成功', duration: 1 })
          }else{
            message.error({ content: '提交失败', duration: 1 })
          }
        }).catch(error => {
          console.log('error', error);
        });

        delete editableData[key];
      };

      //文件上传
      const tokenKey = localStorage.getItem("token_key");
      const token = localStorage.getItem("token")
      const headers = {
        "Authorization": token,
        "Authorization-key": tokenKey
      };
      let handleKey;
      const handleChange = info => {
        let resFileList = [...info.fileList];
        let fileids = "";
        resFileList.map(file => {
          if (file.response) {
            file.url = file.response.data.path;
            if(fileids.length > 0){
              fileids += "," + file.response.data.id;
            } else {
              fileids += file.response.data.id;
            }
          }
          return file;
        });
        if ("zhaobiaowj" === colName){
          editableData[handleKey].zhaobiaowj = fileids;
        } else if("hetongwj" === colName){
          editableData[handleKey].hetongwj = fileids;
        }
      }

      let colName;
      const handleClick = (name) => {
        colName = name
      }

      return{
        tableRef,

        columns,
        dataSource,
        pagination,

        handleAdd,
        onDelete,
        edit,
        baocun,
        editableData,
        cancel,

        handleChange,
        headers,
        handleClick,
      }
    }
  }
</script>
<style>
  .editable-row-operations a {
    margin-right: 8px;
  }
</style>
